<template>
  <div class="did-h">
    <el-card>
      <el-button size="medium" type="primary" @click="showAddRoleDialog">新建角色</el-button>
      <div style="margin-top: 1%;">
        <el-table :data="tableData" class="full-width-table">
        <el-table-column prop="id" label="角色ID" width="200" align="center" sortable></el-table-column>
        <el-table-column prop="name" label="角色名" width="200" align="center"></el-table-column>
        <el-table-column prop="description" label="职责描述" width="400" align="center"></el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="300" align="center"></el-table-column>
        <el-table-column  label="角色操作" align="center">
          <template slot-scope="scope">
            <el-button @click="getPermissionListBychainRole(scope.row)" type="text" size="small">管理权限</el-button>
            <el-button @click="handleEdit(scope.row)" type="text" size="small">修改角色</el-button>
            <el-button @click="deleteRole(scope.row)" type="text" size="small">删除角色</el-button>
          </template>
        </el-table-column>
      </el-table>
      </div>


      <!-- 分页工作 -->
      <div class="block" style="margin-top: 20px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pageNum" :page-size="pageSize" layout="total, prev, pager, next" :total="total"></el-pagination>
      </div>

      <el-dialog title="新建角色" :visible.sync="dialogVisible" width="500px">
        <el-form>
          <el-form-item label="角色名">
            <el-input v-model="newRole.name"></el-input>
          </el-form-item>
          <el-form-item label="职责描述">
            <el-input v-model="newRole.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <!-- 添加 @click="addRole" 事件处理程序 -->
          <el-button type="primary" @click="addRole">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="修改角色" :visible.sync="editRoleDialogVisible">
        <el-form>
          <el-form-item label="旧角色名" align="center">
            <el-input v-model="editRoleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="新角色名" align="center">
            <el-input v-model="editRoleForm.newName"></el-input>
          </el-form-item>
          <el-form-item label="职责描述" align="center">
            <el-input v-model="editRoleForm.description"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">保存</el-button>
        </span>
      </el-dialog>
      <el-dialog title="删除角色" :visible.sync="deleteRoleDialogVisible">
        <p>确定删除该角色吗？</p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deleteRoleDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteRole">确定</el-button>
        </span>
      </el-dialog>

      <div>
        <!-- Dialog 管理权限-->
        <el-dialog title="管理权限" :visible.sync="manageRoleDialogVisible" width="40%">
          <span style="display: flex; margin-left: 85%">
            <el-button type="primary" @click="openDialog()" size="small">增加权限</el-button>
          </span>
          <!-- 中部表单 -->
          <el-table :data="rolePermission" style="width: 100%; margin-top: 20px; max-height: 400px; overflow-y: auto" fit>
            <el-table-column prop="id" label="权限ID" align="center"></el-table-column>
            <el-table-column prop="name" label="权限名" align="center"></el-table-column>
            <el-table-column prop="description" label="职权限描述" align="center"></el-table-column>
            <el-table-column prop="operation" label="操作" align="center"></el-table-column>
            <el-table-column prop="object" label="对象" align="center"></el-table-column>

            <el-table-column prop="object" label="管理操作" align="center">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRolePermission(scope.row)" type="text" size="small">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-dialog title="管理权限" :visible.sync="PreDialogVisible" width="20%" append-to-body>
            <el-cascader ref="cascader" clearable :options="permissionOptions" :props="Props" @change="handleCascaderChange" style="width: 100%"></el-cascader>
            <span slot="footer" class="dialog-footer">
              <el-button @click="PreDialogVisible = false">取消</el-button>
              <el-button type="danger" @click="addRolePermission">确定</el-button>
            </span>
          </el-dialog>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>
  
<script>
export default {
  created() {
    this.getPremission();
  },
  data() {
    return {
      //增加权限
      PreDialogVisible: false,
      manageRoleDialogVisible: false,
      addPermission: [],
      // jwl:弹窗数据
      formInline: {
        user: '',
        region: '',
      },
      rolePermission: [],
      //当前进行权限管理的角色
      modifyRole: '',
      currentPage: 1,
      pageSize: 15,
      showShowBox: false,
      searchInput: '',
      activeName: 'first',
      total: 0,
      tableData: [],
      tableData1: [],
      dialogVisible: false,
      editRoleDialogVisible: false,
      deleteRoleDialogVisible: false,
      permissionDialogVisible: false,
      newRole: {
        name: '',
        description: '',
      },
      editRoleForm: {
        name: '',
        newName: '',
        description: '',
      },
      deleteRoleId: '',
      //级联选择器
      //选项
      permissionOptions: [],
      //选项属性
      Props: {
        multiple: true,
        value: 'name',
        label: 'name',
      },
      pageNum: 1,
    };
  },
  mounted() {
    this.showRoleData(1, 1, 1);
  },
  methods: {
    openDialog() {
      this.PreDialogVisible = true;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.showRoleData(1, 1, this.currentPage); // 根据新的页码重新获取数据
    },

    closeShow() {
      this.showShowBox = false;
    },
    // jwl:弹窗方法结束
    showAddRoleDialog() {
      this.dialogVisible = true;
    },
    async showRoleData(id, name) {
      let formData = new FormData();
      formData.append('id', id);
      formData.append('name', name);
      formData.append('pageNum', this.pageNum);
      formData.append('pageSize', this.pageSize);
      try {
        let res = await this.$http.post(this.$api.userIdentity.showRoleData, formData);
        if (res.status === 200) {
          this.tableData = res.data.records; // 请求成功后将res.data赋值给tableData
          this.total = res.data.total;
          console.log(res.data);
        }
      } catch (error) {
        console.error(error);
      }
    },
    handleEdit(row) {
      console.log(this.editRoleForm);
      this.editRoleForm = { ...row };
      console.log(this.editRoleForm);
      this.editRoleDialogVisible = true; // 显示弹窗
    },
    handleDeleteConfirm(row) {
      this.deleteRoleId = row.id;
      this.deleteRoleDialogVisible = true; // 显示确认删除的弹窗
    },
    async addRole() {
      // 创建包含新角色详情的表单数据对象
      const formData = new FormData();
      formData.append('name', this.newRole.name);
      formData.append('description', this.newRole.description);
      // 向后端发起POST请求
      try {
        const response = await this.$http.post(this.$api.userIdentity.addRole, formData);

        // 处理来自后端的成功响应
        if (response.status === 200) {
          const newRoleData = {
            did: 'new-did',
            id: response.data.id, // 假设后端返回了新创建角色的ID
            name: this.newRole.name,
            description: this.newRole.description,
          };
          // 将新角色数据添加到tableData
          this.tableData.push(newRoleData);
          // 重置newRole对象并隐藏对话框
          this.newRole = {
            name: '',
            sector: '',
          };
          this.dialogVisible = false;
        }
      } catch (error) {
        console.error(error);
        // 在这里处理错误，显示错误消息等
      }
    },
    async saveRole() {
      console.log(this.editRoleForm);
      const formData = new FormData();
      formData.append('name', this.editRoleForm.name);
      if (this.editRoleForm.newName === undefined) {
        console.info('undefined');
        formData.append('newName', '');
      } else {
        formData.append('newName', this.editRoleForm.newName);
      }
      formData.append('description', this.editRoleForm.description);
      try {
        const response = await this.$http.post(this.$api.userIdentity.saveRole, formData);
        if (response.status === 200) {
          // Handle successful response (if needed)
          this.editRoleDialogVisible = false;
        }
      } catch (error) {
        console.error(error);
        // Handle any errors here
      }
    },
    async deleteRole(row) {
      // 创建包含删除角色ID的表单数据对象
      const formData = new FormData();
      formData.append('id', row.id);
      formData.append('name', row.name);
      try {
        const response = await this.$http.post(this.$api.userIdentity.deleteRole, formData);
        if (response.status === 200) {
          this.tableData = this.tableData.filter((row) => row.id !== this.deleteRoleId);
          this.deleteRoleDialogVisible = false;
        }
      } catch (error) {
        console.error(error);
      }
      this.showRoleData(1, 1, 1);
    },
    async handleSearch() {
      const formData = new FormData();
      formData.append('name', this.searchInput);
      try {
        // 发起到后端的 POST 请求
        const response = await this.$http.post('http://localhost:8081/role/findrole', formData); //搜索
        console.log('============================');
        this.tableData = response;
        console.log(response);
        console.log(this.tableData);
        console.log('============================');
      } catch (error) {
        console.error(error);
      }
    },
    //获取角色权限
    async getPermissionListBychainRole(row) {
      this.modifyRole = row.name;
      this.manageRoleDialogVisible = true;
      this.currentRole = row.id;
      const role = {
        role: row.name,
      };
      let res = await this.$http.post(this.$api.userIdentity.getPermissionByRole, role);
      if (res.code == 200) {
        this.rolePermission = res.data;
        console.info(this.rolePermission);
      }
    },
    //添加角色权限
    async addRolePermission() {
      //二维转变一维
      let Data = this.addPermission.flat();
      console.info(Data);
      const params = {
        roleName: this.modifyRole,
        permissionsName: Data,
        operationStatus: 0,
      };
      console.info(params);

      let res = await this.$http.post(this.$api.userIdentity.rolePermissions, params);
      if (res.code == 200) {
        const params = {
          name: this.modifyRole,
          id: this.currentRole,
        };

        this.getPermissionListBychainRole(params);

        this.$message({
          showClose: true,
          message: '添加成功',
          type: 'success',
        });
        this.addPermission = null;
        this.PreDialogVisible = false;
        this.$refs.cascader.$refs.panel.clearCheckedNodes();
      } else {
        this.$message({
          showClose: true,
          message: '添加失败',
          type: 'warning',
        });
      }
    },
    //删除角色权限
    async deleteRolePermission(row) {
      const params = {
        roleName: this.modifyRole,
        permissionsName: [row.name],
        operationStatus: 1,
      };
      console.info(params);
      let res = await this.$http.post(this.$api.userIdentity.rolePermissions, params);
      if (res.code == 200) {
        const params = {
          name: this.modifyRole,
          id: this.currentRole,
        };

        this.getPermissionListBychainRole(params);

        this.$message({
          showClose: true,
          message: '删除成功',
          type: 'success',
        });
      } else {
        this.$message({
          showClose: true,
          message: '删除失败',
          type: 'warning',
        });
      }
    },
    //获取权限列表
    async getPremission() {
      let formdata = new FormData();
      formdata.append('pageNum', 1);
      formdata.append('pageSize', 1000);
      let res = await this.$http.post(this.$api.userIdentity.getPermissionsList, formdata);
      if (res.status == 200) {
        this.permissionOptions = res.data.records;
        console.info('级联');
        console.info(this.permissionOptions);
      }
    },
    //获取级联选择器1的数值 选择的参与用户
    handleCascaderChange(selectedValues) {
      this.addPermission = selectedValues;
      console.log('Selected  permission values:', this.addPermission);
    },
  },
};
</script>
  
<style lang="less" scoped>
.did-h {
  .black {
    &.black-h {
      height: 80%;
    }
  }

  .el-row {
    &.mt3 {
      margin-top: 3rem;
    }
  }

  .small-input {
    width: 180px;
  }

  //  jwl:弹窗样式
  .showBox {
    width: 1000px;
    height: 600px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -500px;
    margin-top: -300px;
    background-color: #f8f8f8;
    padding: 30px;
    z-index: 9999999999999999;
    border-radius: 7px;
  }

  .shadow {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 9999999;
  }

  .close {
    width: 30px;
    height: 30px;
    // background-color: pink;
    position: absolute;
    top: 12px;
    right: 12px;
  }

  .close img {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  //  jwl:弹窗样式
}
</style>
  